﻿<?php
class SysWebsiteManageAction extends CommonAction{

      /*+----------------------------------------------------------------------------------------------------------------
        |      新建站点步骤：
        +----------------------------------------------------------------------------------------------------------------
        |      0.获取功能树
        +----------------------------------------------------------------------------------------------------------------
        |      1.接收处理from表单值（检查账号和密码是不是都是英文，长度是否符合标准）
        +----------------------------------------------------------------------------------------------------------------
        |      2.检查用户信息是否有重复
        +----------------------------------------------------------------------------------------------------------------
        |      3.检查站点信息是否有重复
        +----------------------------------------------------------------------------------------------------------------
        |      4.检查生成的数据库名称是否存在
        +----------------------------------------------------------------------------------------------------------------
        |      5.系统数据库中添加用户信息（状态为：1，类型为：0）
        +----------------------------------------------------------------------------------------------------------------
        |      6.检查用户信息是否添加成功（是否返回添加成功后的ID），添加失败，返回错误
        +----------------------------------------------------------------------------------------------------------------
        |      7.系统数据库中添加站点信息
        +----------------------------------------------------------------------------------------------------------------
        |      8.检查站点信息是否添加成功（同上），添加失败，删除新添加的用户信息，返回错误
        +----------------------------------------------------------------------------------------------------------------
        |      9.创建站点数据库
        +----------------------------------------------------------------------------------------------------------------
        |      10.检查数据库是否创建成功，失败，删除用户信息，删除站点信息，返回错误
        +----------------------------------------------------------------------------------------------------------------
        |      11.添加功能信息
        +----------------------------------------------------------------------------------------------------------------
        |      12.检查功能信息是否添加成功，失败，删除用户信息，删除站点信息，删除数据库，返回失败
        +----------------------------------------------------------------------------------------------------------------
        |      13.站点数据库中添加用户信息
        +----------------------------------------------------------------------------------------------------------------
        |      14.检查站点数据库中的用户信息是否添加成功，失败，删除系统数据库中的用户信息，站点信息，站点数据库
        +----------------------------------------------------------------------------------------------------------------
        |      15.站点数据库中添加角色信息（用户组）
        +----------------------------------------------------------------------------------------------------------------
        |      16.检查站点数据库中的角色信息是否添加成功，失败，删除系统数据库中的用户信息，站点信息，站点数据库
        +----------------------------------------------------------------------------------------------------------------
        |      17.创建其他表，并导入相关数据
        +----------------------------------------------------------------------------------------------------------------
        |      18.执行复制站点文件
        +----------------------------------------------------------------------------------------------------------------
        |      19.检查站点文件是否复制成功
        +----------------------------------------------------------------------------------------------------------------
        |      20.修改站点文件的配置文件（采用写入）
        +----------------------------------------------------------------------------------------------------------------
        |      21.检查配置文件是否写入成功，失败，则删除站点文件，删除系统数据库中的用户信息，站点信息，站点数据库
        +----------------------------------------------------------------------------------------------------------------
        |      22.返回站点创建站点成功
        +----------------------------------------------------------------------------------------------------------------
       */
    public function addWebsite(){
        //0.获取功能树
        $this->getFunctionTree();
        if($_POST['create']){
            //1.接收处理from表单值（检查账号和密码是不是都是英文，长度是否符合标准）
            $content = $this->disposeFormArray($_POST);
            //2.检查用户信息是否有重复
            $this->checkUserInfo($content['sysuser_name']);
            //3.检查站点信息是否有重复
            $this->checkWebsiteInfo($content['website_name']);
            //4.检查生成的数据库名称是否存在
            $this->checkWebsiteDatabaseName($content['database']);
            //5.系统数据库中添加用户信息（状态为：1，类型为：0）
            $add['sysuser'] = $this->addSysuserInfo($content);
            //6.系统数据库中添加站点信息
            $add['website'] = $this->addWebsiteInfo($content,$add);
            //7.创建站点数据库
            $add['create_table'] = $this ->create_database($content['database']);
            //8.添加站点用户信息和用户组信息
            $this->insertUserAndGroup($content);
            //9.复制站点文件
            $this->copyWebsiteDir($content);
            //10.修改站点配置文件
            $this->editWebsiteConfig($content);

            $this->success("创建站点成功！");
        }
        
        $this->display();
      }

      /*+---------------------------+
        |      站点模板管理         |
        +---------------------------+*/
      public function manageWebsiteTemplate(){
             
             $this->display();
      }

      /*+---------------------------+
        |    站点数据统计           |                     
        +---------------------------+*/
      public function websiteDateStatistics(){
             
             $this->display();
      }

      /*+-----------------------------+
        |      0.获取功能树           |
        +-----------------------------+*/
      public function getFunctionTree(){
            $addition['link']  = "0";
            $addition['after'] = "<input type='checkbox' name='Fid[]' value='PK'>";
            $function          = $this->get_menu(136,$addition);   //获取功能树
            $this ->assign("function",$function);
      }
      /*+-------------------------------------------------------------------------------+
        |      1.接收处理from表单值（检查账号和密码是不是都是英文，长度是否符合标准）   |
        +-------------------------------------------------------------------------------+*/
      public function disposeFormArray($_POST){
          foreach($_POST as $key => $val){
               if($key == "sysuser_password"){
                       $content[$key] = MD5($val);
               }elseif($key == "Fid"){
                       foreach($val as $key =>$val){
                            $Fid .= $val.",";
                       }
                       $content['function'] = rtrim($Fid,",");
               }else{
                       $content[$key] = $val;
               }
          }
          
          $databaseName  = "dhjdsj_douhao_";
          $databaseName .= strtolower($this->pinyin($_POST['website_name']));
          $databaseName .= "_".time();
          $content['database']    = $databaseName;
          $content['create_time'] = toDate(time());
          $content['create_user'] = $_SESSION[C("USER_AUTH_KEY")];
          //echo "<pre>";
          //print_r($content);
          return $content;
            
      }

      /*+----------------------------------------+
        |     2.检查用户信息是否有重复           |
        +----------------------------------------+*/
      public function checkUserInfo($sysuser_name){
             //$database = new Model();
             //$database ->query("use dhjdsj_douhaosystem");
             $sysuser   = D("sysuser");
             $checkUser = $sysuser ->where("sysuser_name = '{$sysuser_name}'")->find();
             if($checkUser){
                  $this->error("用户名已经存在，请重新输入！");
             }
      }
      /*+----------------------------------------+
        |     3.检查站点信息是否有重复           |
        +----------------------------------------+*/
      public function checkWebsiteInfo($website_name){
             //$database = new Model();
             //$database ->query("use dhjdsj_douhaosystem");
             $website       = D("website");
             $websiteName   = $website ->where("website_name = '{$website_name}'")->find();
             if($websiteName){
                    $this->error("站点名称已经存在，请重新重新填写！");
             }
      }
      /*+----------------------------------------+
        |     4.检查生成的数据库名称是否存在     |
        +----------------------------------------+*/
      public function checkWebsiteDatabaseName($databaseName){
             $database      = new Model();
             $databa        = $database->query("show databases");
             foreach($databa as $key => $val){
                    if($val['Database'] == "{$databaseName}"){
                            $this->error("数据库创建失败，有相同的库存在，请重命名站点名称！");
                    }
             }
             $database ->query("use dhjdsj_douhaosystem");  //切回系统数据库
      }
      /*+---------------------------------------------------------+
        |    5.系统数据库中添加用户信息（状态为：1，类型为：0）   |
        +---------------------------------------------------------+*/
      public function addSysuserInfo($content){
             $sysuser              = D("sysuser");
             $data                 = array();
             $data['sysuser_name'] = $content['sysuser_name'];
             $data['user_type']    = "0";
             $data['function']     = $content['function'];
             $data['database']     = $content['database'];
             $data['sysuser_password'] = $content['sysuser_password'];
             $data['create_time']  = $content['create_time'];
             $data['create_user']  = $content['create_user'];
             $addUser = $sysuser ->add($data);
             if(!$addUser){
                    $this->error("创建用户失败！");
             }else{
                 return $addUser;
             }
      }

      /*+----------------------------------+
        |    7.系统数据库中添加站点信息    |
        +----------------------------------+*/
      public function addWebsiteInfo($content,$id){
             $website = D("website");
             $data['website_name'] = $content['website_name'];
             $data['uid']          = $id['sysuser'];
             $data['database']     = $content['database'];
             $data['create_user']  = $content['create_user'];
             $data['create_time']  = $content['create_time'];
             $addWeb  = "";
             $addWeb  = $website ->add($data);
             if(!$addWeb){
                  $this->error("创建站点名称失败！");
                  $website ->delete($id['sysuser']);
             }else{
             	  $this->updSysuerWid($data['uid'],$addWeb);
                  return $addWeb;
             }
      }
      /*+--------------------------+
        |    修改站点信息的UID     |
        +--------------------------+*/
      public function editSysuserId($add){
             $website     = D("sysuser");
             $data        = array();
             $data['id']  = $add['sysuser'];
             $data['Wid'] = $add['website']; 
             $updateWeb   = $website ->save($data);
             if(!$updateWeb){
                    $this -> error("修改用户的站点ID，失败！");
             }
      }
      /*+---------------------------+
        |     9.创建站点数据库      |
        +---------------------------+
       */
      public function create_database($databaseName){
          $createTable = new Model();
          //1 => 创建站点的数据库
          $createTable ->query("create database {$databaseName}");
          //2 => 切换到站点的数据库
          $createTable ->query("use {$databaseName}");
          //3 => 创建功能表
          $SQL  = "
CREATE TABLE IF NOT EXISTS `douhao_function` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `pid` varchar(50) NOT NULL DEFAULT '0' COMMENT '父ID',
  `path` varchar(100) NOT NULL DEFAULT '0' COMMENT '无限分类路径',
  `function_entry` varchar(50) NOT NULL DEFAULT 'admin/index.php' COMMENT '功能入口',
  `function_act` varchar(50) NOT NULL COMMENT '功能名称',
  `function_title` varchar(50) NOT NULL COMMENT '功能标题',
  `function_app` varchar(50) CHARACTER SET latin1 NOT NULL COMMENT '功能链接路径',
  `function_abstruct` text NOT NULL COMMENT '功能说明',
  `status` enum('0','1') NOT NULL DEFAULT '1' COMMENT '状态：1=>显示，0=>不显示',
  `position` int(5) NOT NULL DEFAULT '88888' COMMENT '位置排序',
  `create_user` int(11) NOT NULL,
  `create_time` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='功能表' AUTO_INCREMENT=163 ;
          ";
          
          $createTable ->query($SQL);
          //4 => 切换到系统数据库，获取站点可拥有的所有功能
          $createTable ->query("use dhjdsj_douhaosystem");
          $SQL  = $this->getFunctionInsertSQL();
          //5 => 切回站点数据库，添加功能信息
          $createTable ->query("use {$databaseName}");
          $createTable ->query($SQL);
          //6 => 创建用户组表
          $SQL  = "CREATE TABLE IF NOT EXISTS `douhao_group` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pid` int(11) NOT NULL DEFAULT '0' COMMENT '父ID',
  `path` varchar(100) NOT NULL COMMENT '无限分类路径',
  `group_name` varchar(50) NOT NULL,
  `group_function` varchar(500) NOT NULL,
  `group_describe` text NOT NULL COMMENT ' 角色简介',
  `create_user` int(11) NOT NULL,
  `create_time` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='角色表' AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
          //7 => 创建站点数据统计表
          $SQL  = "CREATE TABLE IF NOT EXISTS `douhao_statistics` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `website_name` varchar(50) NOT NULL COMMENT '站点名称',
  `add_num` int(11) NOT NULL COMMENT '新增数',
  `update_num` int(11) NOT NULL COMMENT '更新数',
  `delete_num` int(11) NOT NULL COMMENT '删除数',
  `create_user` int(11) NOT NULL COMMENT '创建人用户ID（管理员）',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='站点统计表' AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
          //8 => 创建站点会员表
          $SQL  = "CREATE TABLE IF NOT EXISTS `douhao_sysmember` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `status` enum('0','1') NOT NULL DEFAULT '1' COMMENT '0:停用，1：正常使用',
  `sysmember_name` varchar(50) NOT NULL COMMENT '用户名',
  `sysmember_nikename` varchar(50) NOT NULL COMMENT '昵称',
  `sysmember_portrait` varchar(10) NOT NULL COMMENT '用户头像（img）',
  `sysmember_password` varchar(50) NOT NULL COMMENT '用户密码',
  `sysmember_email` varchar(50) NOT NULL COMMENT '用户邮箱',
  `sysmember_describe` text NOT NULL COMMENT '用户描述',
  `last_login_time` datetime NOT NULL COMMENT '最后登录时间',
  `last_login_ip` varchar(40) NOT NULL COMMENT '最后登录IP',
  `login_count` mediumint(8) NOT NULL COMMENT '登录次数统计',
  `create_member` int(11) NOT NULL COMMENT '创建人用户ID（管理员）',
  `	update_time` datetime NOT NULL COMMENT '修改时间',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
          //9 => 创建站点用户表
          $SQL  = "CREATE TABLE IF NOT EXISTS `douhao_sysuser` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `status` enum('0','1') NOT NULL DEFAULT '1' COMMENT '0:停用，1：正常使用',
  `user_type` enum('0','1') NOT NULL COMMENT '类型:1=>系统管理员；0=>站点管理员',
  `Gid` int(11) NOT NULL COMMENT '角色ID',
  `Wid` int(5) NOT NULL COMMENT '站点ID',
  `function` varchar(1000) NOT NULL COMMENT '用户功能',
  `database` varchar(50) NOT NULL COMMENT '数据库名称',
  `sysuser_name` varchar(50) NOT NULL COMMENT '系统管理员用户名',
  `sysuser_nikename` varchar(50) NOT NULL COMMENT '昵称',
  `sysuser_password` varchar(50) NOT NULL COMMENT '系统管理员用户密码',
  `sysuser_email` varchar(50) NOT NULL COMMENT '系统管理员邮箱',
  `sysuser_describe` text NOT NULL COMMENT '管理员描述',
  `last_login_time` datetime NOT NULL COMMENT '最后登录时间',
  `last_login_ip` varchar(40) NOT NULL COMMENT '最后登录IP',
  `login_count` mediumint(8) NOT NULL COMMENT '登录次数统计',
  `create_user` int(11) NOT NULL COMMENT '创建人用户ID（管理员）',
  `update_time` datetime NOT NULL COMMENT '修改时间',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
          //10 => 创建站点模板表
          $SQL  = "CREATE TABLE IF NOT EXISTS `douhao_template` (
  `id` int(11) NOT NULL,
  `template_name` varchar(50) NOT NULL COMMENT '模板名称',
  `template_describe` text NOT NULL COMMENT '模板简介',
  `template_url` varchar(50) NOT NULL COMMENT '模板存储路径',
  `template_img` varchar(50) NOT NULL COMMENT '模板样图（路径）',
  `create_user` int(11) NOT NULL COMMENT '创建人用户ID（管理员）',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='模板信息表' AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
          //11 => 创建站点信息表
          $SQL  = "CREATE TABLE IF NOT EXISTS `douhao_website` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `website_name` varchar(50) NOT NULL COMMENT '站点名称',
  `website_template` varchar(50) NOT NULL COMMENT '站点模板ID',
  `create_user` int(11) NOT NULL COMMENT '创建人用户ID（管理员）',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='站点名称表' AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
          //12 => 创建商店地址表
          $SQL  = "CREATE TABLE IF NOT EXISTS `douhao_website_address` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `column_id` int(11) NOT NULL COMMENT '栏目ID',
  `shop_name` varchar(50) NOT NULL COMMENT '商店名称',
  `shop_address` varchar(200) NOT NULL COMMENT '地址',
  `shop_telno` varchar(20) NOT NULL COMMENT '电话',
  `shop_describe` text NOT NULL COMMENT '简介',
  `shop_content` text NOT NULL COMMENT '内容',
  `status` enum('0','1') NOT NULL DEFAULT '0' COMMENT '状态（0:不显示；1:显示）',
  `create_time` varchar(30) NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='商店地址' AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
          //13 => 创建文章表
          $SQL  = "CREATE TABLE IF NOT EXISTS `douhao_website_article` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `column_id` int(11) NOT NULL COMMENT '栏目ID',
  `article_name` varchar(100) NOT NULL COMMENT '标题',
  `article_describe` text NOT NULL COMMENT '简介',
  `article_content` text NOT NULL COMMENT '内容',
  `status` enum('0','1') NOT NULL COMMENT '状态',
  `create_time` varchar(30) NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='文章表' AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
          //14 => 创建栏目表
          $SQL  = "CREATE TABLE IF NOT EXISTS `douhao_website_column` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `column_name` varchar(50) NOT NULL COMMENT '栏目名称',
  `status` enum('0','1') NOT NULL DEFAULT '0' COMMENT '状态（0:不显示；1:显示）',
  `column_type` varchar(50) NOT NULL COMMENT '栏目属性',
  `column_act` varchar(50) NOT NULL COMMENT 'act',
  `column_app` varchar(50) NOT NULL COMMENT 'app',
  `column_tablename` varchar(50) NOT NULL COMMENT '存储栏目内容的表名',
  `column_position` int(11) DEFAULT '88888' COMMENT '栏目排序',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='站点栏目表' AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
         
          //16 => 添加新闻表
          $SQL = "CREATE TABLE IF NOT EXISTS `douhao_website_news` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `column_id` int(11) NOT NULL COMMENT '栏目ID',
  `news_name` varchar(100) NOT NULL COMMENT '标题',
  `news_describe` text NOT NULL COMMENT '简介',
  `news_content` text NOT NULL COMMENT '内容',
  `status` enum('0','1') NOT NULL DEFAULT '0' COMMENT '状态',
  `create_time` varchar(30) NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='新闻表' AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);

          //17 => 添加产品表
          $SQL = "CREATE TABLE IF NOT EXISTS `douhao_website_product` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `column_id` int(11) NOT NULL COMMENT '栏目ID',
  `product_name` varchar(100) NOT NULL COMMENT '产品名称',
  `product_num` varchar(50) NOT NULL COMMENT '产品货号',
  `product_color` varchar(50) NOT NULL COMMENT '产品颜色',
  `product_size` varchar(50) NOT NULL COMMENT '产品尺码',
  `product_material` varchar(50) NOT NULL COMMENT '产品材质',
  `product_composition` varchar(50) NOT NULL COMMENT '产品成分',
  `product_describe` text NOT NULL COMMENT '产品简介',
  `status` enum('0','1') NOT NULL COMMENT '状态（0:不显示；1:显示）',
  `create_time` varchar(30) NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='产品表' AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
          //18 => 添加配置表
          $SQL = "CREATE TABLE IF NOT EXISTS `douhao_website_config` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `column_id` int(11) NOT NULL COMMENT '栏目ID',
  `pid` int(11) NOT NULL,
  `config_name` varchar(50) NOT NULL,
  `config_info` varchar(1000) NOT NULL,
  `create_time` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='站点配置表' AUTO_INCREMENT=117 ;";
          $createTable ->query($SQL);
          //19 => 添加站内链接表
          $SQL = "CREATE TABLE IF NOT EXISTS `douhao_website_link` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `link_name` varchar(50) NOT NULL COMMENT '链接名称',
  `ifUseImage` enum('0','1') NOT NULL DEFAULT '0' COMMENT '是否使用图片',
  `link_imageSize` varchar(20) NOT NULL DEFAULT '0x0' COMMENT '图片大小',
  `link_image` varchar(100) NOT NULL COMMENT '链接图片',
  `link_url` varchar(100) NOT NULL COMMENT '链接url',
  `create_time` varchar(30) NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='站点链接表' AUTO_INCREMENT=1 ;";
          $createTable ->query($SQL);
          //20 => 添加服务器运行日志表
          $SQL = "CREATE TABLE IF NOT EXISTS `douhao_log` (
  `cid` mediumint(9) NOT NULL COMMENT '栏目id',
  `action` varchar(20) NOT NULL COMMENT '操作 add delete update',
  `operateid` int(11) NOT NULL COMMENT '被操作数据id',
  `desc` varchar(100) NOT NULL DEFAULT '' COMMENT '描述',
  `dateline` int(11) NOT NULL COMMENT '操作时间'
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='服务器运行日志表';";
          $createTable ->query($SQL);
          //21 => 添加站点数据统计表
          $SQL = "CREATE TABLE IF NOT EXISTS `douhao_static` (
  `cid` int(11) NOT NULL COMMENT '栏目id',
  `add_num` int(11) NOT NULL DEFAULT '0' COMMENT '新增数',
  `update_num` int(11) NOT NULL DEFAULT '0' COMMENT '更新数',
  `delete_num` int(11) NOT NULL DEFAULT '0' COMMENT '删除数',
  `last_operate_time` datetime NOT NULL COMMENT '最后操作时间',
  PRIMARY KEY (`cid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='站点统计表';";
         $createTable ->query($SQL);

      }

      /*+------------------------------------+
        |      10.添加用户和用户组           |
        +------------------------------------+
       */
      public function insertUserAndGroup($content){
             $insert   = new Model();
             $insert   ->query("use {$content['database']}");  //切换到新建的站点数据库
             //1 => 添加用户信息
             $addUser  = "INSERT INTO `douhao_sysuser` (`status`, `user_type`, `Gid`, `Wid`, `function`, `database`, `sysuser_name`, `sysuser_nikename`, `sysuser_password`, `sysuser_email`, `sysuser_describe`, `last_login_time`, `last_login_ip`, `login_count`, `create_user`, `update_time`, `create_time`) VALUES
                 ('1', '1', 1, 0, '', '{$content['database']}', '{$content['sysuser_name']}', '系统管理员', '{$content['sysuser_password']}', '', '', '0000-00-00 00:00:00', '', 0, 1, '0000-00-00 00:00:00', '{$content['create_time']}');";
             
             $user = $insert   ->query($addUser);
             //2 =>添加用户组信息
             $addGroup = "INSERT INTO `douhao_group` (`pid`, `path`, `group_name`, `group_function`, `group_describe`, `create_user`, `create_time`) VALUES
                 (0, '', '超级管理员', '{$content['function']}', '', 1, '{$content['create_time']}');";
             $group = $insert  ->query($addGroup);
             //3 => 添加站点固定栏目信息
             $val = array("(1, '关于我们', '0', 'aboutUs', '', '', 'website_article', 88888, '2012-01-30 21:58:49');",
                       "(2, '新闻中心', '0', 'newsCenter', '', '', 'website_news', 88888, '2012-01-30 22:14:18');",
                       "(3, '产品专区', '0', 'productArrondi', '', '', 'website_product', 88888, '2012-01-30 22:15:51');",
                       "(4, '商店地址', '0', 'shopAddress', '', '', 'website_address', 88888, '2012-01-30 22:17:02');",
                       "(5, '网上商城', '0', 'link', '', '', '', 88888, '2012-01-30 22:18:19');",
                       "(6, '招商合作', '0', 'canvassBusinessOrders', '', '', 'website_article', 88888, '2012-01-30 22:26:21');",
                       "(7, '服务中心', '0', 'serviceCentre', '', '', 'website_article', 88888, '2012-01-30 22:28:25');",
                       "(8, '人才招聘', '0', 'personnelRecruitment', '', '', 'website_news', 88888, '2012-01-30 22:29:22');",
                       "(9, '联系我们', '0', 'connectUs', '', '', 'website_article', 88888, '2012-01-30 22:31:18');",
                       "(10, '网站地图', '0', 'link', '', '', '', 88888, '2012-01-30 22:35:59');"
                   );
             foreach($val as $key => $v){
                  $SQL = "INSERT INTO `douhao_website_column` (`id`, `column_name`, `status`, `column_type`, `column_act`, `column_app`, `column_tablename`, `column_position`, `create_time`) VALUES".$v;
                  $insert ->query($SQL);
             }
             //4 => 添加站点配置信息
             $SQL = "INSERT INTO `douhao_website_config` (`id`, `column_id`, `pid`, `config_name`, `config_info`, `create_time`) VALUES
(1, 0, 0, '站点配置', '', ''),
(2, 0, 0, '文件上传管理', '', ''),
(3, 0, 0, '图片水印管理', '', ''),
(4, 2, 2, '上传方式', '1', ''),
(5, 2, 2, '允许上传大小', '2', ''),
(6, 2, 2, '允许上传类型', 'gif|png|jpg|jpeg', ''),
(7, 2, 2, '是否生成缩略图', '1', ''),
(9, 2, 2, '生成缩略图大小', '30x30', ''),
(10, 3, 2, '上传方式', '', ''),
(11, 3, 2, '允许上传大小', '2', ''),
(12, 3, 2, '允许上传类型', 'gif|png|jpg|jpeg', ''),
(13, 3, 2, '是否生成缩略图', '1', ''),
(15, 3, 2, '生成缩略图大小', '30x30', ''),
(16, 4, 2, '上传方式', '1', ''),
(17, 4, 2, '允许上传大小', '2', ''),
(18, 4, 2, '允许上传类型', '', ''),
(19, 4, 2, '是否生成缩略图', '0', ''),
(21, 4, 2, '生成缩略图大小', '', ''),
(22, 1, 2, '上传方式', '1', ''),
(23, 1, 2, '允许上传大小', '2', ''),
(24, 1, 2, '允许上传类型', 'gif|png|jpg|jpeg', ''),
(25, 1, 2, '是否生成缩略图', '1', ''),
(27, 1, 2, '生成缩略图大小', '30×30', ''),
(28, 6, 2, '上传方式', '', ''),
(29, 6, 2, '允许上传大小', '', ''),
(30, 6, 2, '允许上传类型', '', ''),
(31, 6, 2, '是否生成缩略图', '', ''),
(82, 1, 3, '水印图片', '', ''),
(33, 6, 2, '生成缩略图大小', '', ''),
(34, 7, 2, '上传方式', '', ''),
(35, 7, 2, '允许上传大小', '', ''),
(36, 7, 2, '允许上传类型', '', ''),
(37, 7, 2, '是否生成缩略图', '', ''),
(39, 7, 2, '生成缩略图大小', '', ''),
(40, 8, 2, '上传方式', '', ''),
(41, 8, 2, '允许上传大小', '', ''),
(42, 8, 2, '允许上传类型', '', ''),
(43, 8, 2, '是否生成缩略图', '', ''),
(80, 1, 3, '设置水印大小', '200x200', ''),
(45, 8, 2, '生成缩略图大小', '', ''),
(46, 9, 2, '上传方式', '', ''),
(47, 9, 2, '允许上传大小', '', ''),
(48, 9, 2, '允许上传类型', '', ''),
(49, 9, 2, '是否生成缩略图', '', ''),
(79, 1, 3, '是否添加水印', '1', ''),
(75, 7, 2, '是否开启独立上传', '0', ''),
(78, 1, 2, '是否开启独立上传', '0', ''),
(77, 9, 2, '是否开启独立上传', '0', ''),
(76, 8, 2, '是否开启独立上传', '0', ''),
(74, 6, 2, '是否开启独立上传', '0', ''),
(73, 4, 2, '是否开启独立上传', '0', ''),
(72, 3, 2, '是否开启独立上传', '0', ''),
(71, 2, 2, '是否开启独立上传', '0', ''),
(70, 9, 2, '生成缩略图大小', '', ''),
(83, 1, 3, '设置水印透明度', '20', ''),
(84, 2, 3, '是否添加水印', '0', ''),
(85, 2, 3, '设置水印大小', '0x0', ''),
(86, 2, 3, '水印图片', '', ''),
(87, 2, 3, '设置水印透明度', '100', ''),
(88, 3, 3, '是否添加水印', '0', ''),
(89, 3, 3, '设置水印大小', '0x0', ''),
(90, 3, 3, '水印图片', '', ''),
(91, 3, 3, '设置水印透明度', '100', ''),
(92, 4, 3, '是否添加水印', '0', ''),
(93, 4, 3, '设置水印大小', '0x0', ''),
(94, 4, 3, '水印图片', '', ''),
(95, 4, 3, '设置水印透明度', '100', ''),
(96, 6, 3, '是否添加水印', '0', ''),
(97, 6, 3, '设置水印大小', '0x0', ''),
(98, 6, 3, '水印图片', '', ''),
(99, 6, 3, '设置水印透明度', '100', ''),
(100, 7, 3, '是否添加水印', '0', ''),
(101, 7, 3, '设置水印大小', '0x0', ''),
(102, 7, 3, '水印图片', '', ''),
(103, 7, 3, '设置水印透明度', '100', ''),
(104, 8, 3, '是否添加水印', '0', ''),
(105, 8, 3, '设置水印大小', '0x0', ''),
(106, 8, 3, '水印图片', '', ''),
(107, 8, 3, '设置水印透明度', '100', ''),
(108, 9, 3, '是否添加水印', '0', ''),
(109, 9, 3, '设置水印大小', '0x0', ''),
(110, 9, 3, '水印图片', '', ''),
(111, 9, 3, '设置水印透明度', '100', ''),
(112, 0, 1, '站点名称', '', ''),
(113, 0, 1, '分页页面最大显示条数', '', ''),
(116, 0, 1, '页脚信息', '', '');";
             $insert ->query($SQL);
             $insert ->query("use dhjdsj_douhaosystem"); //切回系统数据库
      }

      /*+---------------------------------------+
        |   9.复制站点统一默认目录文件          |
        +---------------------------------------+*/
      public function copyWebsiteDir($content){
             import("@.ORG.Dir");
             $source       = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/DefineWebsite";
             $destination  = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/Website/".$content['database']."/";
             $copyDir      = new Dir();
             $copyDir      ->copyDir($source,$destination);	
			 //删除站点目录里的其他文件（指默认站点文件目录里的文件，若出现在站点目录内，将它们删除）
		     $dir = new Dir($source);
		     $dirInfo = $dir ->toArray();
		     foreach($dirInfo as $key => $val){
			     if($val['type'] == "dir"){
					 $content['website_files'][$key]['dir'] = $val['filename'];
			     }
				 if($val['type'] == "file"){
				     $content['website_files'][$key]['file'] = $val['filename'];	 
			     }
	         }	  
      }

      /*+---------------------------------------+
        |   10.修改站点配置文件                 |
        +---------------------------------------+*/
      public function editWebsiteConfig($content){

             $config = '<?php
$config	=	require "../../config.php";
$array  =  array(
	"DB_NAME"               => "'.$content['database'].'"'.',//站点数据库
    "TMPL_SWITCH_ON"	    => true,	  // 启用多模版支持
	"TMPL_DETECT_THEME"     => true,      // 自动侦测模板主题
);
return array_merge($config,$array);
?>';
             $websiteDir = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/Website/".$content['database']."/Conf/config.php";
             $fp = fopen($websiteDir, "w");  //以只写的方式打开文件，获取文件指针
		     if (flock($fp, LOCK_EX)) {    //获取文件的独立锁定
   				fwrite($fp, $config);        //向指定的文件中写入文本内容
    					flock($fp, LOCK_UN);   //获取文件的释放锁定
				} else {                               
    					echo "不能锁定文件!";   //如果锁定失败则返回错误信息
				}
				fclose($fp);	                 //关闭文件指针
      }
      /**
       * 更改用户表站点id
       * @param unknown_type $id
       * @param unknown_type $wid
       */
      private function updSysuerWid($id,$wid)
      {
          $obj = D('Sysuser');
          $obj->where('id = '.$id)->save(array('Wid'=>$wid));
      }
      /**
       * 站点列表
       */
      public function listWebsite()
      {
      	  $siteName = isset($_GET['sitename']) ? trim($_GET['sitename']) : '';
      	  $obj = D('Website');
      	  $list = $obj->getWebsite($siteName);//dump($list);
      	  $this->assign('list',$list);
      	  $this->assign('siteName',$siteName);
          $this->display();
      }
	  /**
	   * 删除站点
	   */
	  public function deleteWebsite()
	  {
			$where['id'] = isset($_GET['id']) ? intval($_GET['id']) : 0;
			if(!$where['id']) $this->error('参数错误！');
			$obj = D('website');
			$webInfo = $obj->where($where)->find();
			//删除用户信息  删除数据库   删除表信息  删除程序文件
			if(!$webInfo) $this->error('该站点信息不存在或已经被删除！');
			//删除用户信息
			$sysuser = M('sysuser');
			$sysuser->where(array('id'=>$webInfo['uid']))->delete();
			//删除数据库
			$result = $obj->query("drop database {$webInfo['database']}");
			$obj->where($where)->delete();
			//删除站点程序
			import("@.ORG.Dir");
			$dirObj = new Dir();
			$direcory = dirname(dirname(dirname(dirname(__FILE__)))).'/WebSite/'.$webInfo['database'];
			if(is_dir($direcory)) $dirObj->delDir($direcory);
			$this->success('站点删除成功！');
	  }
      
	  /**
       * 数据统计
       */
      public function dataStatic()
      {
      	  $siteName = isset($_GET['sitename']) ? trim($_GET['sitename']) : '';
      	  $obj = D('Website');
      	  $list = $obj->getWebsite($siteName);
      	  $this->assign('list',$list);
      	  $this->assign('siteName',$siteName);
          $this->display();
      }
      /**
       * 统计列表
       */
      public function dataStaticList()
      {
      	  $userType = intval($_SESSION['user_type']);
      	  //如果不是系统管理员查看
      	  if($userType == 0)
      	  {
      	  	$model = D('Static');
      	  	$list = $model->getStaticList();
      	  	dump($list);
      	  }else
      	  {
      	      $where['id'] = isset($_GET['id']) ? intval($_GET['id']) : 0;
      	  	  if(!$where['id']) $this->error('非法访问！');
      	  	  $obj = D('website');
      	  	  $webInfo = $obj->field('database')->where($where)->find();
			  if(!$webInfo) $this->error('该站点信息不存在或已经被删除！');
			  if(!$webInfo['database']) $this->error('该站点信息不存在或已经被删除！');
      	  	  $obj->query('use '.$webInfo['database']);
      	  	  $model = D('Static');
      	  	  $list = $model->getStaticList();
      	  	  $this->assign('list',$list);
      	  }
      	  $this->display();
      }
}

?>
